#include <iostream>
using namespace std;

#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>

int g_money = 100;
//线程的资源是共享的
void *handleThread(void *arg)
{
    // int num = *(int*)arg;
    int num = 0;
    while(g_money > 0)
    {   
        g_money -= 1;
        printf("thread1 g_money = %d\n",g_money);
        sleep(1);
    }
#if 0
    while(1)
    {
        printf("num = %d\n",num);
        num+=2;

        sleep(2);
    }
#endif
    pthread_exit(NULL);
    return NULL;
}

void *handleThread1(void *arg)
{   
    pthread_detach(pthread_self());
    // int num = *(int*)arg;
    int num = 0;
    while(g_money > 0)
    {   
        g_money -= 1;
        printf("thread2 g_money = %d\n",g_money);
        

        sleep(1);
    }
    return NULL;
}

int main()
{   
#if 0
    //线程号
    pthread_t threadId = pthread_self();

    cout<<"threadId:"<<threadId<<endl;
    //进程号
    pid_t pidId = getpid();
    cout<<"pidId:"<<pidId<<endl;
#endif
    //创建线程
    pthread_t threadId;
    int ret = pthread_create(&threadId,NULL,handleThread,NULL);
    if(ret != 0)
    {
        perror("thread create error:");
        exit(-1);
    }

    pthread_t threadId1;
    ret = pthread_create(&threadId1,NULL,handleThread1,NULL);
    if(ret != 0)
    {
        perror("thread create error:");
        exit(-1);
    }
#if 0
    //回收线程资源
    //一旦线程号已经被分离，pthread_join不能够再回收其线程资源
    pthread_join(threadId,NULL);
    pthread_join(threadId1,NULL);
#endif
    cout<<"hello world"<<endl;
    int cnt = 100;
    while(cnt--)
    {
        // printf("l am main process!\n");
        sleep(1);
        if(cnt == 90)
        {
            pthread_cancel(threadId1);
        }
    }
    return 0;
}